<template>
  <a-spin :spinning="tableLoading">
    <a-tabs v-model:activeKey="data.activeKey">
      <a-tab-pane key="1" tab="概要">
        <a-card class="app" >
          <a-row justify="space-between" style="margin-bottom: 20px">
            <a-col :span="12">
              <a-space :size="20">
                <h3>电键：{{ data.form.id }}</h3>
                <h3>对象名称：采购退货通知单</h3>
                <h3>状态：{{ data.form.docStatus }}</h3>
                <h3>审核：{{ data.form.approved ? '已审核' : '未审核' }}</h3>
              </a-space>
            </a-col>
            <a-col :span="12">
              <a-row justify="end">
                <a-button-group>
                  
                  <a-button
                    @click="save()"
                    v-if="!(data.form.docStatus === 'L' || data.form.docStatus === 'C' || data.form.approved || !data.form.edit)"
                    >保存
                  </a-button>
                  <a-button
                    @click="edit()"
                    v-if="!(data.form.docStatus === 'L' || data.form.docStatus === 'C' || data.form.approved || data.form.edit)"
                    >编辑
                  </a-button>
                  <a-button @click="del()" v-if="data.form.docStatus === 'O' && !data.form.approved && !data.form.edit">删除</a-button>
                  <a-button @click="approved()" v-if="!data.form.edit">审核</a-button>
                  <a-dropdown>
                    <a-button v-if="!(data.form.edit || data.form.docStatus === 'L')">更多</a-button>
                    <template #overlay>
                      <a-menu @click="more">
                        <a-menu-item key="a" v-if="data.form.docStatus !== 'C'">关闭单据</a-menu-item>
                        <a-menu-item key="b" v-if="data.form.docStatus === 'C'">打开单据</a-menu-item>
                        <a-menu-item key="c" v-if="!data.form.approved">发起审核</a-menu-item>
                        <a-menu-item key="d" v-if="data.form.approved">取消审核</a-menu-item>
                        <a-menu-item key="e">创建采购退货单</a-menu-item>
                      </a-menu>
                    </template>
                  </a-dropdown>
                  <a-button @click="refresh" value="7"> 刷 新</a-button>
                </a-button-group>
              </a-row>
            </a-col>
          </a-row>

          <a-form ref="formRef" :model="data.form" :rules="data.rules" :label-col="{ span: 4 }">
            <a-row class="smart-query-form-row">
              <a-col :span="6">
                <a-form-item label="月期间" name="absId">
                  <span>{{ data.form.absId }}</span>
                </a-form-item>
                <a-form-item label="部门" name="deptId">
                  <DepartmentTreeSelect v-if="data.form.edit" :init="false" v-model:value="data.form.deptId" @update:value="change" />
                  <span v-else>{{ data.form.deptName }}</span>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="制单">
                  <span>{{ data.form.createBy + '&nbsp;&nbsp;' + data.form.createTime }}</span>
                </a-form-item>
                <a-form-item label="修改">
                  <span>{{ data.form.updateBy + '&nbsp;&nbsp;' + data.form.updateTime }}</span>
                </a-form-item>
                <a-form-item label="备注">
                  <a-textarea v-if="data.form.edit" v-model:value="data.form.remark" :rows="2" />
                  <span v-else>{{ data.form.remark }}</span>
                </a-form-item>
              </a-col>
              <a-col :span="8"></a-col>
            </a-row>
          </a-form>
          <a-row>
            <a-button-group></a-button-group>
            <a-table
              style="width: 100%"
              :dataSource="data.form.lista"
              :columns="columnsa"
              rowKey="lineNum"
              :scroll="{ y: 650, x: 600 }"
              :pagination="{
                showSizeChanger: true,
                pageSizeOptions: ['20', '30', '40', '50', '100'],
                defaultPageSize: 20,
                showQuickJumper: true,
              }"
            >
              <template #bodyCell="{ text, record, column }">
                <template v-if="column.dataIndex === 'qty'">
                  <a-input-number
                    v-if="record.edit"
                    style="width: 200px"
                    v-model:value="record.qty"
                    :step="0.01"
                    :min="1"
                    @change="qtyChange(record)"
                  />
                  <span v-else>{{ record.qty }}</span>
                </template>
                <template v-if="column.dataIndex === 'price'">
                  <a-input-number
                    v-if="record.edit"
                    style="width: 200px"
                    v-model:value="record.price"
                    :step="0.01"
                    :min="1"
                    @change="priceChange(record)"
                  />
                  <span v-else>{{ record.price }}</span>
                </template>
                <template v-if="column.dataIndex === 'priceLine'">
                  <span>{{ record.priceLine }}</span>
                </template>

                <template v-if="column.dataIndex === 'taxPrice'">
                  <a-input-number
                    v-if="record.edit"
                    style="width: 200px"
                    v-model:value="record.taxPrice"
                    :step="0.01"
                    :min="1"
                    @change="taxPriceChange(record)"
                  />
                  <span v-else>{{ record.taxPrice }}</span>
                </template>

                <template v-if="column.dataIndex === 'taxPriceLine'">
                  <span>{{ record.taxPriceLine }}</span>
                </template>

                <template v-if="record.edit && column.dataIndex === 'freeTxt'">
                  <a-input v-model:value="record.freeTxt" />
                </template>
                <template v-if="record.edit && column.dataIndex === 'reqDate'">
                  <a-date-picker valueFormat="YYYY-MM-DD" v-model:value="record.reqDate" />
                </template>

                <template v-if="record.edit && column.dataIndex === 'quality'">
                  <a-select style="width: 100%" v-model:value="record.quality" name="quality">
                    <a-select-option value="A">合格</a-select-option>
                    <a-select-option value="B">让步接收</a-select-option>
                    <a-select-option value="C">不合格</a-select-option>
                  </a-select>
                </template>

                <template v-if="record.edit && column.dataIndex === 'action'">
                  <a-button @click="lineaDel(record)" danger type="link">
                    <DeleteOutlined />
                  </a-button>
                </template>
              </template>
            </a-table>
          </a-row>
        </a-card>
      </a-tab-pane>
      <a-tab-pane key="2" tab="凭证">
        <a-row :gutter="24">
          <a-col :span="12">
            <a-card title="基础凭证">
              <a-table
                style="width: 100%"
                :dataSource="data.form.listb"
                :columns="columnsb"
                rowKey="lineNum"
                :scroll="{ y: 650, x: 600 }"
                :pagination="false"
              >
                <template #bodyCell="{ text, record, column }">
                  <template v-if="column.dataIndex === 'id'">
                    <a-button type="link" @click="showForm(record, 'saorda')">{{ text }}</a-button>
                  </template>
                </template>
              </a-table>
            </a-card>
          </a-col>
          <a-col :span="12">
            <a-card title="目标凭证">
              <a-table
                style="width: 100%"
                :dataSource="data.form.listc"
                :columns="columnsc"
                rowKey="lineNum"
                :scroll="{ y: 650, x: 600 }"
                :pagination="false"
              >
                <template #bodyCell="{ text, record, column }">
                  <template v-if="column.dataIndex === 'id'">
                    <a-button type="link" @click="showForm(record, 'stoordaback')">{{ text }}</a-button>
                  </template>
                </template>
              </a-table>
            </a-card>
          </a-col>
        </a-row>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
  <!--  <Approvord :approvedData="data.approvedData" :visible="data.visible.approvord" :on-close="onclose"></Approvord>-->
</template>
<script setup>
  import { onMounted, reactive, ref, computed } from 'vue';
  import { message, Modal, Form } from 'ant-design-vue';
  import { smartSentry } from '/src/lib/smart-sentry';
  import { approvordApi } from '/src/api/business/erp/approvord-api';
  import { useRouter, useRoute } from 'vue-router';
  import DepartmentTreeSelect from '/src/components/system/department-tree-select/index.vue';
  import Approvord from '/src/components/business/erp/approved.vue';
  import { goodsApi } from '/src/api/business/goods/goods-api.js';

  import { subordbackApi } from '/src/api/business/erp/subordback-api.js';

  import { stoordApi } from '/src/api/business/erp/stoord-api.js';
  import { saordApi } from '/src/api/business/erp/saord-api.js';

  const route = useRoute();
  const router = useRouter();
  const data = reactive({
    form: {
      id: 0,
      objId: '',
      absId: '',
      approved: false,
      docStatus: 'O',
      vendId: null,
      vendName: null,
      deptId: null,
      deptName: null,
      edit: false,
      createById: null,
      createBy: '',
      createTime: '',
      updateById: null,
      updateBy: '',
      updateTime: '',

      lista: [],
      listb: [],
      listc: [],
    },
    radioGroup: null,
    rules: {
      deptId: [{ required: true, message: '请选择部门' }],
      macName: [{ required: true, message: '请输入设备名称' }],
      macAddress: [{ required: true, message: '请输入设备地址' }],
    },
    model: {
      absId: '',
    },
    doc: {
      tm: 'subordback',
      tda: 'subordaback',
    },
    editableData: {
      nowDate: null,
    },
    visible: {
      approvord: false,
    },
    approvedData: {
      baseEntry: null,
      tabName: null,
    },
    itemList: [],
    chooseLinea: null,
    activeKey: '1',
  });
  const columnsa = ref([
    {
      title: '行号',
      dataIndex: 'lineNum',
      align: 'center',
      width: 100,
    },
    {
      title: '物料编码',
      dataIndex: 'itemId',
      width: 250,
      align: 'left',
    },
    {
      title: '物料名称',
      dataIndex: 'itemName',
      width: 300,
      align: 'left',
    },
    {
      title: '规格',
      dataIndex: 'specs',
      width: 400,
      align: 'left',
      ellipsis: true,
    },
    {
      title: '数量',
      dataIndex: 'qty',
      width: 250,
      align: 'center',
    },
    {
      title: '单位',
      dataIndex: 'unit',
      width: 120,
    },
    {
      title: '系统批次',
      dataIndex: 'batchId',
      width: 160,
    },
    {
      title: '行状态',
      dataIndex: 'lineStatus',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      width: 100,
    },
  ]);
  const columnsb = ref([
    {
      title: '基础编码',
      dataIndex: 'id',
      align: 'center',
      width: 100,
    },
    {
      title: '基础行号',
      dataIndex: 'lineNum',
      width: 250,
      align: 'right',
    },
    {
      title: '物料编码',
      dataIndex: 'itemId',
      width: 300,
      align: 'right',
    },
    {
      title: '物料名称',
      dataIndex: 'itemName',
      width: 300,
      align: 'right',
    },
    {
      title: '数量',
      dataIndex: 'qty',
      width: 120,
      align: 'right',
    },
  ]);
  const columnsc = ref([
    {
      title: '目标编码',
      dataIndex: 'id',
      align: 'center',
      width: 100,
    },
    {
      title: '目标行号',
      dataIndex: 'lineNum',
      width: 250,
      align: 'right',
    },
    {
      title: '物料编码',
      dataIndex: 'itemId',
      width: 300,
      align: 'right',
    },
    {
      title: '物料名称',
      dataIndex: 'itemName',
      width: 300,
      align: 'right',
    },
    {
      title: '数量',
      dataIndex: 'qty',
      width: 120,
      align: 'right',
    },
  ]);
  const tableLoading = ref(false);
  const formRef = ref(null);

  // 初始化
  function init() {
    if (route.query.type === 'info') {
      data.form.id = route.query.id;
      queryData();
    } else if (route.query.type === 'tager') {
      saordApi
        .infoUnexecuteBack(route.query.id)
        .then((res) => {
          // 主表
          data.form.deptId = res.data.deptId;
          data.form.deptName = res.data.deptName;
          data.form.approved = false;
          data.form.docStatus = 'O';
          data.form.edit = true;
          // 明细
          res.data.lista.forEach((item) => {
            data.form.lista.push({
              id: data.form.id,
              lineNum: data.form.lista.length + 1,
              lineStatus: 'O',
              qty: item.qty,
              specs: item.specs,

              unit: item.unit,
              itemId: item.itemId,
              itemName: item.itemName,
              baseId: item.id,
              baseLineNum: item.lineNum,
              tax: 1.13,
              price: 0,
              priceLine: 0,
              taxPrice: 0,
              taxPriceLine: 0,
              edit: true,
            });
          });
        })
        .finally(() => {});
    } else {
      data.form.edit = true;
    }
  }

  // 更多操作
  function more({ key }) {
    // 审核处理函数
    if (key === 'a') {
      data.form.docStatus = 'C';
      tableLoading.value = true;
      subordbackApi.update(data.form).then((res) => {
        tableLoading.value = false;
        queryData();
      });
    } else if (key === 'b') {
      data.form.docStatus = 'O';
      tableLoading.value = true;
      subordbackApi.update(data.form).then((res) => {
        tableLoading.value = false;
        queryData();
      });
    } else if (key === 'c') {
      approvordApi
        .add({
          id: 0,
          approvLineNum: 2,
          approvType: 'A',
          baseEntry: data.form.id,
          tabName: data.form.objName,
          docStatus: 'O',
          tabId: data.form.objId,
          baseVersion: data.form.version,
        })
        .then((res) => {
          queryData();
        });
    } else if (key === 'd') {
      approvordApi
        .add({
          id: 0,
          approvLineNum: 2,
          approvType: 'B',
          baseEntry: data.form.id,
          tabName: data.form.objName,
          docStatus: 'O',
          tabId: data.form.objId,
          baseVersion: data.form.version,
        })
        .then((res) => {
          queryData();
        });
    } else if (key === 'e') {
      router.push({ path: 'stoordaback', query: { type: 'tager', id: data.form.id } });
    }
  }

  function save() {
    formRef.value.validate()
      .then(() => {
        tableLoading.value = true;
        if (data.form.id) {
          subordbackApi
            .update(data.form)
            .then((res) => {
              queryData(data.form.id);
              message.success('修改成功！');
            })
            .finally(() => {
              tableLoading.value = false;
            });
        } else {
          subordbackApi
            .add(data.form)
            .then((res) => {
              data.form.id = res.data;
              message.success('保存成功！');
              router.push({ path: data.doc.tda, query: { type: 'info', id: res.data } });
              queryData(res.data);
            })
            .finally(() => {
              tableLoading.value = false;
            });
        }
      })
      .catch((err) => {
        message.error('页面校验失败！');
      });
  }

  function edit() {
    data.form.edit = true;

    data.form.lista.forEach((item) => {
      item.edit = true;
    });
  }

  function del() {
    if (data.form.listc.length !== 0) {
      message.error('请先删除目标凭证！');
    } else {
      Modal.confirm({
        content: `确认删除（${data.form.id}）`,
        onOk() {
          subordbackApi.delete(data.form.id).then((res) => {
            message.success('删除成功！');
            router.push({ path: data.doc.tm });
          });
        },
        cancelText: '取消',
        onCancel() {
          Modal.destroyAll();
        },
      });
    }
  }

  async function queryData() {
    tableLoading.value = true;
    formRef.value.resetFields();
    try {
      let queryResult = await subordbackApi.info(data.form.id);
      data.form = queryResult.data;
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      tableLoading.value = false;
    }
  }

  function refresh() {
    queryData();
  }

  function back() {
    router.push({ path: data.doc.tm });
  }

  function change(item, key) {
    data.form.deptName = key;
  }

  // 审核------------------------------------------------------------------------------------------------
  function approved() {
    data.approvedData.baseEntry = data.form.id;
    data.approvedData.tabName = data.form.objName;
    data.visible.approvord = true;
  }

  function onclose() {
    data.visible.approvord = false;
    queryData();
  }

  // 行----------------------------------------------a-------------------------------------------------------

  function priceChange(item) {
    item.taxPrice = (item.price * item.tax).toFixed(4);
    item.priceLine = (item.qty * item.price).toFixed(4);
    item.taxPriceLine = (item.price * item.tax * item.qty).toFixed(4);
  }

  function taxPriceChange(item) {
    item.price = (item.taxPrice / item.tax).toFixed(4);
    item.priceLine = (item.qty * item.price).toFixed(4);
    item.taxPriceLine = (item.taxPrice * item.qty).toFixed(4);
  }

  function qtyChange(item) {
    item.priceLine = (item.qty * item.price).toFixed(4);
    item.taxPriceLine = (item.taxPrice * item.tax * item.qty).toFixed(4);
  }

  function itemFocus(item) {
    data.chooseLinea = item;
  }

  function itemChange(item, it) {
    data.chooseLinea.itemName = it.key.goodsName;
    data.chooseLinea.specs = it.key.specs;
    data.chooseLinea.unit = it.key.unit;
  }

  function queryItemList() {
    goodsApi
      .queryGoodsList({
        pageNum: 1,
        pageSize: 10,
      })
      .then((res) => {
        data.itemList = res.data.list;
      })
      .catch((err) => {})
      .finally(() => {});
  }

  function lineaEdit(key) {
    key.edit = true;
  }

  function lineaAdd() {
    data.form.lista.push({
      id: data.form.id,
      lineNum: data.form.lista.length + 1,
      lineStatus: 'O',
      qty: 1,
      edit: true,
    });
  }

  function lineaDel(item) {
    data.form.lista.splice(item.lineNum - 1, 1);
    for (let i = item.lineNum - 1; i < data.form.lista.length; i++) {
      data.form.lista[i].lineNum = data.form.lista[i].lineNum - 1;
    }
  }

  // --------------------------------凭证

  function showForm(data, it) {
    router.push({ path: it, query: { type: 'info', id: data.id } });
  }

  onMounted(() => {
    init();
    queryItemList();
  });
</script>
